/**
 * Created by Jaye on 2018/6/7.
 */

var todayMatchs = 0;
var userCount = 0;
var myRank = 0;
var myPoint = 0;
var todayGuessMatch = [];
var allMatch = [];
var myMatch = [];
$(document).ready(function () {
    // user();
    initTodayTable();
    initScoreList();
    listenTodayMatchTable();
    initTodayMatch();
    initListScore();
    initMyRankAndPoint();
    initMyPointTable();
    initMyPoint();
    // setMatchGuessState(0);
    $('#allMatch').on('show.bs.modal', function () {
        if (allMatch.length == 0) {
            initModal();
        }
    });
    $('#guessBtn').click(function (e) {
        e.preventDefault();
        var l = Ladda.create(this);
        l.start();
        l.setProgress(0 - 1);
        guess(l);
    });
    $('#loginout').click(function (e) {
        loginout();
    });
});
function listenTodayMatchTable() {
    $('#todayMatchList').on('click-row.bs.table', function (e, row, element) {
        clickMatch(row.matchId);
    });
}
function setMatchGuessState(state) {
    if (state == 1) {
        $("#matchGuessState").attr("class", "label label-info pull-right");
        $("#matchGuessState").html("已竞猜");
    } else {
        $("#matchGuessState").attr("class", "label label-danger pull-right");
        $("#matchGuessState").html("未竞猜");
    }
}
function setTodayMatch() {
    $('#todayMatchs').html(todayGuessMatch.length);
}
function setUserCount() {
    $('#userCount').html(userCount);
}
function setMyRank() {
    $('#myRank').html(myRank);
}
function initMyRankAndPoint() {
    var url = "guess/myself";
    ajax(url, {}, function (data) {
        if (data.code === 1000) {
            myRank = data.data.rownum;
            myPoint = data.data.scoreCount;
            setMyRank();
            setMyPoint();
        } else {
            swal({
                title: "加载数据发生错误",
                type: "error"
            });
        }
    });
}
function setMyPoint() {
    $('#myPoint').html(myPoint);
}
function clickMatch(matchId) {
    // alert(matchId);
    for (var i = 0; i < todayGuessMatch.length; i++) {
        if (todayGuessMatch[i].matchId == matchId) {
            setMatchInfo(matchId,
                todayGuessMatch[i].playExplain,
                todayGuessMatch[i].hostTeamName,
                todayGuessMatch[i].guestTeamName,
                todayGuessMatch[i].guessHostScore,
                todayGuessMatch[i].guessGuestScore,
                todayGuessMatch[i].guessState);
            var guessState = 1;
            if ((todayGuessMatch[i].guessHostScore == "" && todayGuessMatch[i].guessGuestScore == "") ||
                (todayGuessMatch[i].guessHostScore == null && todayGuessMatch[i].guessGuestScore == null)) {
                guessState = 0;
            }
            setMatchGuessState(guessState);
        }
    }
}
function initListScore() {
    var url = "/guess/list/score";
    var postData = {"data": ""};
    ajax(url, postData, function (data) {
        if (data.code == 1000) {
            refreshSocreList(data.data);
        } else {
            swal({
                title: "积分榜数据加载失败，请刷新重试或联系管理员！",
                type: "error"
            });
        }
    });
}
function refreshSocreList(socreList) {
    $('#scoreList').bootstrapTable('load', socreList);
    userCount = socreList.length;
    setUserCount();
}

function refreshScoreList() {
    initListScore();
}
function refreshMyGuess() {
    initMyPoint();
}
function initScoreList() {
    $("#scoreList").bootstrapTable({
        height: "300",
        iconSize: "outline",
        columns: [
            {
                field: 'rownum',
                title: '排 名',
                align: "center",
                formatter: function (value, row, index) {
                    return '<p><span class="badge badge-warning">' + value + '</span> </p>';
                }
            }, {
                field: 'userName',
                title: '用 户',
                align: "center"
            }, {
                field: 'scoreCount',
                title: '积 分',
                align: "center",
                formatter: function (value, row, index) {
                    return '<p><span class="badge badge-info">' + value + '</span> </p>';
                }
            }
        ]
    });
}
function loginout() {
    ajax("user/loginout", {}, function (data) {
        if (data.code == 1000) {
            swal({
                title: "注销成功",
                type: "success",
                confirmButtonText: "确认",
                closeOnConfirm: false
            }, function () {
                window.location.href = "/index";
            });
        } else {
            swal({
                title: data.msg,
                type: "error"
            });
        }
    });
}
function initMyPoint() {
    var url = "guess/myguess/list";
    ajax(url, {}, function (data) {
        if (data.code === 1000) {
            myMatch = data.data;
            $('#myPointTable').bootstrapTable('load', myMatch);
            $('#myGuessMatch').html("竞猜场次: " + myMatch.length);
        }
    });
}
function initMyPointTable() {
    $("#myPointTable").bootstrapTable({
        height: "220",
        search: true,
        iconSize: "outline",
        columns: [
            {
                field: 'SerialNumber',
                title: '序号',
                align: "center",
                formatter: function (value, row, index) {
                    return index + 1;
                }
            }, {
                field: 'matchId',
                title: '场次号',
                align: "center",
                visible: false
            }, {
                title: "比赛时间",
                field: "playTime",
                align: "center",
                formatter: function (value, row, index) {
                    return changeDateFormat(value)
                }
            }, {
                title: "说明",
                field: "playExplain",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == '小组赛') {
                        return '<p><span class="badge badge-primary">' + value + '</span> </p>';
                    } else if (value == '半决赛') {
                        return '<p><span class="badge badge-success">' + value + '</span> </p>';
                    } else if (value == '决赛') {
                        return '<p><span class="badge badge-warning">' + value + '</span> </p>';
                    } else {
                        return '<p><span class="badge badge-info">' + value + '</span> </p>';
                    }
                }
            },
            {
                title: "对阵信息",
                field: "fightTeam",
                align: "center"
            }, {
                title: "比赛状态",
                field: "matchState",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == '1') {
                        return '<p><span class="badge badge-danger">已结束</span> </p>';
                    }
                    return '<p><span class="badge badge-primary">未开始</span> </p>';
                }
            }, {
                title: "最终比分",
                field: "matchScore",
                align: "center"
            }, {
                title: "竞猜比分",
                field: "guessScore",
                align: "center"
            }, {
                title: "获得积分",
                field: "point",
                align: "center"
            }, {
                title: "积分状态",
                field: "pointState",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == '1') {
                        return '<p><span class="badge badge-primary">已核算</span> </p>';
                    }
                    return '<p><span class="badge badge-danger">未核算</span> </p>';
                }
            }, {
                title: "积分链状态",
                field: "chainState",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == '1') {
                        return '<p><span class="badge badge-primary">已上链</span> </p>';
                    }
                    return '<p><span class="badge badge-danger">未上链</span> </p>';
                }
            }
        ]
    })
    ;
}
function initTodayTable() {
    $("#todayMatchList").bootstrapTable({
        height: "650",
        iconSize: "outline",
        columns: [
            {
                field: 'SerialNumber',
                title: '序号',
                align: "center",
                formatter: function (value, row, index) {
                    return index + 1;
                }
            }, {
                field: 'matchId',
                title: '场次号',
                align: "center",
                visible: false
            }, {
                title: "比赛时间",
                field: "playTime",
                align: "center",
                formatter: function (value, row, index) {
                    return changeDateFormat(value)
                }
            }, {
                title: "场次说明",
                field: "playExplain",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == '小组赛') {
                        return '<p><span class="badge badge-primary">' + value + '</span> </p>';
                    } else if (value == '半决赛') {
                        return '<p><span class="badge badge-success">' + value + '</span> </p>';
                    } else if (value == '决赛') {
                        return '<p><span class="badge badge-warning">' + value + '</span> </p>';
                    } else {
                        return '<p><span class="badge badge-info">' + value + '</span> </p>';
                    }
                }
            },
            {
                title: "组别",
                field: "hostTeamId",
                align: "center"
            }, {
                title: "队名",
                field: "hostTeamName",
                align: "center"
            }, {
                title: "组别",
                field: "guestTeamId",
                align: "center"
            }, {
                title: "队名",
                field: "guestTeamName",
                align: "center"
            }, {
                title: "状态",
                field: "guessState",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == 1) {
                        return '<p><span class="badge badge-danger">停止竞猜</span> </p>';
                    }
                    return '<p><span class="badge badge-primary">竞猜中</span> </p>';
                }
            }, {
                title: "预测得分",
                field: "guessHostScore",
                align: "center"
            },
            {
                title: "预测得分",
                field: "guessGuestScore",
                align: "center"
            }
        ]
    })
    ;
}
function changeDateFormat(cellval) {
    var dateVal = cellval + "";
    if (cellval != null) {
        var date = new Date(parseInt(dateVal.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

        return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
    }
}
function initTodayMatch() {
    var url = "/guess/list/allow";
    var postData = {"data": ""};
    ajax(url, postData, function (data) {
        if (data.code == 1000) {
            todayGuessMatch = data.data;
            $('#todayMatchList').bootstrapTable('load', todayGuessMatch);
            setMatchInfo(todayGuessMatch[0].matchId,
                todayGuessMatch[0].playExplain,
                todayGuessMatch[0].hostTeamName,
                todayGuessMatch[0].guestTeamName,
                todayGuessMatch[0].guessHostScore,
                todayGuessMatch[0].guessGuestScore,
                todayGuessMatch[0].guessFlag);
            setTodayMatch();
        } else {
            swal({
                title: "今日场次数据加载错误，请刷新重试或联系管理员！",
                type: "error"
            });
        }
    });
}
function refreshTodayTable() {
    var url = "/guess/list/allow";
    var postData = {"data": ""};
    ajax(url, postData, function (data) {
        if (data.code == 1000) {
            todayGuessMatch = data.data;
            $('#todayMatchList').bootstrapTable('load', todayGuessMatch);
            setTodayMatch();
        } else {
            swal({
                title: "今日场次数据加载错误，请刷新重试或联系管理员！",
                type: "error"
            });
        }
    });
}
function setMatchInfo(matchId, playExplain,
                      hostTeamName, guestTeamName,
                      myHostTeamPoint, myGuestTeamPoint, guessState) {
    $('#guessMatchId').val(matchId);
    $('#playExplain').html(playExplain);
    $('#hostTeamName').html(hostTeamName);
    $('#guestTeamName').html(guestTeamName);
    $('#myHostTeamPoint').val(myHostTeamPoint);
    $('#myGuestTeamPoint').val(myGuestTeamPoint);
    setMatchGuessState(guessState);
}
function ajax(url, reqData, Func) {
    $.ajax(
        {
            url: url,
            data: reqData,
            type: "post",
            // async: false,
            dataType: "json",
            // contentType: "application/json;charset=UTF-8",
            beforeSend: function () {
            },
            success: function (data) {
                Func(data);
            },
            error: function () {
                swal({
                    title: "请求出错！",
                    type: "error"
                });
            }
        });
}
function listMatch() {
    $('#allMatch').modal('show');
}
function showMyPoint() {
    alert(1);
}
function initModal() {
    initModalTables();
    var url = "match/list/all";
    var postData = {"data": ""};
    ajax(url, postData, function (data) {
        if (data.code == 1000) {
            allMatch = data.data;
            $('#allMatchList').bootstrapTable('load', allMatch);
        } else {
            swal({
                title: "数据加载失败！！！",
                type: "error"
            });
        }
    });
}
function initModalTables() {
    var tablName = "allMatchList";
    tableInit(tablName);
}
function guess(ladda) {
    var matchId = $('#guessMatchId').val();
    var myHostTeamPoint = $('#myHostTeamPoint').val();
    var myGuestTeamPoint = $('#myGuestTeamPoint').val();
    if (myHostTeamPoint == null || myGuestTeamPoint == null
        || myHostTeamPoint === "" || myGuestTeamPoint === ""
        || myHostTeamPoint < 0 || myGuestTeamPoint < 0) {
        swal({
            title: "输入参数有误！！！",
            type: "error"
        });
        ladda.stop();
        return;
    }
    if (!isNaN(myHostTeamPoint) && !isNaN(myGuestTeamPoint)) {
        if (myHostTeamPoint >= 0 && myGuestTeamPoint >= 0) {
            submitMyGuess(ladda, matchId, Number(myHostTeamPoint), Number(myGuestTeamPoint));
        }
    } else {
        swal({
            title: "输入参数有误！！！",
            type: "error"
        });
        ladda.stop();
    }
    // ladda.stop();
}
function submitMyGuess(ladda, matchId, hostPoint, guestPoint) {
    var url = "guess/create";
    var post = new Array;
    var guess = new MyGuess(matchId, hostPoint, guestPoint);
    // post.push(guess);
    // var postData = {"guess": guess};
    ajax(url, guess, function (data) {
        if (data.code == 1000) {
            swal({
                title: "竞猜成功",
                type: "success"
            }, function () {
                ladda.stop();
            });
            refreshTodayTable();
            setMatchGuessState(1);
        } else {
            swal({
                title: data.msg,
                type: "error"
            });
            ladda.stop();
        }
    });
}
// function updateTodayGuessMatch(matchId) {
//     todayGuessMatch;
// }
function MyGuess(matchId, hostScore, guestScore) {
    this.matchId = matchId;
    this.hostScore = hostScore;
    this.guestScore = guestScore;
}
function tableInit(tableName) {
    $("#" + tableName + "").bootstrapTable({
        height: "500",
        search: true,
        iconSize: "outline",
        columns: [
            {
                field: 'SerialNumber',
                title: '序号',
                align: "center",
                formatter: function (value, row, index) {
                    return index + 1;
                }
            }, {
                field: 'matchId',
                title: '场次号',
                align: "center",
                visible: false
            }, {
                title: "比赛时间",
                field: "playTime",
                align: "center",
                formatter: function (value, row, index) {
                    return changeDateFormat(value)
                }
            },
            {
                title: "组别",
                field: "hostTeamId",
                align: "center"
            }, {
                title: "队名",
                field: "hostTeamName",
                align: "center"
            }, {
                title: "组别",
                field: "guestTeamId",
                align: "center"
            }, {
                title: "队名",
                field: "guestTeamName",
                align: "center"
            }, {
                title: "状态",
                field: "matchState",
                align: "center",
                formatter: function (value, row, index) {
                    if (value == 1) {
                        return '<p><span class="badge badge-danger">已结束</span> </p>';
                    }
                    return '<p><span class="badge badge-primary">未开始</span> </p>';
                }
            }, {
                title: "得分",
                field: "hostScore",
                align: "center"
            }, {
                title: "得分",
                field: "guestScore",
                align: "center"
            }
        ]
    })
    ;
}
